package com.phifan.book_zdmm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Timer;
import com.phifan.book_zdmm.R;
import com.util.zdmm.CutArray;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class PageActivity extends Activity {

	private static final String TEMP = "temp";
	TextView content;
	TextView check;
	int chapterWhi;
	Timer timer;
	// AdView youmi;
	// DomobAdView domob;
	int viAdId = 0;
	Handler handler;
	RelativeLayout adLy;
	private final int pageCharNum = 300;
	private int totalNum;
	private int pageWhi = 0;
	private String chapter;
	private int comeStatus = 0;
	private int maxChapter = 0;

	@SuppressWarnings("unused")
	private void randomAd() {
		// youmi = (AdView) findViewById(R.id.youmiAd);
		// domob = (DomobAdView) findViewById(R.id.domobAd);
		// Random rdm = new Random();
		// ad = rdm.nextBoolean();
		// if(ad == true){
		// youmi.setVisibility(View.GONE);
		// }else{
		// domob.setVisibility(View.GONE);
		// }
		// System.out.println(ad);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.out.println("oncreate");
		setContentView(R.layout.page);
		content = (TextView) findViewById(R.id.book_text);
		check = (TextView) findViewById(R.id.check);
		// randomAd();
		Intent intent = getIntent();
		if (intent.getExtras() != null) {
			chapterWhi = intent.getExtras().getInt("chapter");
			pageWhi = intent.getExtras().getInt("page");
			comeStatus = intent.getExtras().getInt("comeStatus");
			maxChapter = intent.getExtras().getInt("maxChapter");
			totalNum = getTotalPageNum(chapterWhi);
			content.setText(read(pageWhi));
		} else {
			content.setText(pageWhi);
		}

		check.setText("第" + (pageWhi + 1) + "页/共" + totalNum + "页");
		final Button next = (Button) findViewById(R.id.next);

		next.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				next.setTextColor(Color.BLACK);
				return false;
			}
		});
		// 设置下一页变为下一章
		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				next.setTextColor(Color.WHITE);
				Log.i("biny", "totalNum:" + totalNum + "pageWhi:" + pageWhi);
				// 判断是不是最后一页
				if (pageWhi >= totalNum - 1) {
					// 判断是不是 最后一章
					if (chapterWhi >= maxChapter - 1) {
						return;
					}
					chapterWhi++;
					pageWhi = 0;
					totalNum = getTotalPageNum(chapterWhi);
					content.setText(read(pageWhi));
					next.setText("下一页");
					check.setText("第" + (pageWhi + 1) + "页/共" + totalNum + "页");
					ScrollView scv = (ScrollView) findViewById(R.id.scrollview);
					scv.scrollTo(0, 0);
					return;
				}

				pageWhi++;
				if (pageWhi >= totalNum - 1 && chapterWhi < maxChapter - 1) {
					next.setText("下一章");
				} else {
					next.setText("下一页");
				}
				content.setText(read(pageWhi));
				check.setText("第" + (pageWhi + 1) + "页/共" + totalNum + "页");
				ScrollView scv = (ScrollView) findViewById(R.id.scrollview);
				scv.scrollTo(0, 0);
			}
		});

		final Button prev = (Button) findViewById(R.id.prev);
		prev.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				prev.setTextColor(Color.BLACK);
				return false;
			}
		});
		prev.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				prev.setTextColor(Color.WHITE);
				if (pageWhi <= 0) {
					Toast.makeText(PageActivity.this, "已是第一页",
							Toast.LENGTH_SHORT).show();
					return;
				}
				pageWhi--;
				// 设置
				if (pageWhi >= totalNum - 1) {
					next.setText("下一章");
				} else {
					next.setText("下一页");
				}
				content.setText(read(pageWhi));
				check.setText("第" + (pageWhi + 1) + "页/共" + totalNum + "页");
				ScrollView scv = (ScrollView) findViewById(R.id.scrollview);
				scv.scrollTo(0, 0);
			}
		});
	}

	public String read(int pageNum) {
		if (pageNum > totalNum - 1) {
			return "";
		}
		if (pageNum == totalNum - 1) {
			return chapter.substring(pageNum * pageCharNum);
		}
		return chapter.substring(pageNum * pageCharNum, pageNum * pageCharNum
				+ pageCharNum);
	}

	// for zero
	/**
	 * @修改BUG 设置关闭流 并且循环字节读取文件
	 * @return
	 */
	private int getTotalPageNum(int chapterNum) {
		InputStream is = null;
		BufferedReader bf=null;
		try {
			is = getAssets().open("book/" + "book.txt");
			//将字节流转化成 字符流
			InputStreamReader reader=new InputStreamReader(is,"gb2312");
			//为了提高速度  用缓冲流读取
			bf=new BufferedReader(reader);
			//定义接收大型数组
			char[] b = new char[is.available()];
			//定义接收小型新数组（用来接收截取之后的数组）
			char[] newArr = null;
			//将缓冲流中的数据处理输入到 b数组中
			bf.read(b,0,is.available());
			//掉用公共方法截取字符串
			CutArray  cut=new CutArray();
			newArr =cut.interceptChar(b,"@str"+chapterNum,"@str"+chapterNum);	
			chapter=new String(newArr);			
			chapter = chapter.replace("<h>", "");
			chapter = chapter.replace("</h>", "");
			chapter = chapter.replace("<a>", "");
			chapter = chapter.replace("</a>", "");
			chapter = chapter.replace("<t>", "");
			chapter = chapter.replace("</t>", "");
			System.out.println(chapter.length() + "pagenum:" + chapter.length()
					/ pageCharNum);
			return chapter.length() / pageCharNum;

		} catch (IOException e) {
			e.printStackTrace();
		} finally
		// 关闭输入流 @liuliang
		{
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return -1;
	}

	@Override
	protected void onStop() {
		SharedPreferences.Editor localEditor1 = getSharedPreferences(TEMP,
				MODE_WORLD_WRITEABLE).edit();
		localEditor1.putInt("chapter", this.chapterWhi);
		localEditor1.putInt("page", this.pageWhi);
		localEditor1.commit();
		Log.i("store", chapterWhi + "");
		super.onStop();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (comeStatus == 1) {
				Intent intent = new Intent();
				intent.setClass(PageActivity.this, MainActivity.class);
				startActivity(intent);
				PageActivity.this.finish();
				return true;
			} else if (comeStatus == 2) {

			}
		}
		return super.onKeyDown(keyCode, event);
	}

}
